package cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @program: algorithm
 * @description:
 * @author: 陈恩涛
 * @create: 2022-08-19 17:21
 **/
public class AtomicStampedReferenceDemo {
    static AtomicStampedReference<Integer> value = new AtomicStampedReference<>(100, 1);

    public static void main(String[] args) {
        new Thread(() -> {
            final int stamp = value.getStamp();
            System.out.println(Thread.currentThread().getName() + "\t 首次版本号" + stamp);
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            value.compareAndSet(100, 101, value.getStamp(), value.getStamp() + 1);
            System.out.println(Thread.currentThread().getName() + "\t 2次版本号" + value.getStamp());

            value.compareAndSet(101, 100, value.getStamp(), value.getStamp() + 1);
            System.out.println(Thread.currentThread().getName() + "\t 3次版本号" + value.getStamp());

        }, "t1").start();

        new Thread(() -> {
            final int stamp = value.getStamp();
            System.out.println(Thread.currentThread().getName() + "\t 首次版本号" + stamp);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            final boolean b = value.compareAndSet(100, 2022, stamp, stamp + 1);
            System.out.println(b + "\t" + value.getReference() + "\t" + value.getStamp());
        }, "t2").start();
    }
}
